/**
 * 云函数：更新 sh_pattern 表的 file_name 字段
 * 路径：uniCloud-aliyun/cloudfunctions/update-pattern-filename/index.js
 */

'use strict';

const db = uniCloud.database()

exports.main = async (event, context) => {
	console.log('开始执行 sh_pattern 表 file_name 字段更新...')
	
	const { action = 'update' } = event
	
	try {
		if (action === 'test') {
			// 测试模式：只查看前几条记录的格式
			return await testPatternFileFormat()
		} else if (action === 'update') {
			// 更新模式：执行实际更新
			return await updatePatternFileNames()
		} else {
			return {
				success: false,
				error: 'Invalid action. Use "test" or "update"'
			}
		}
	} catch (error) {
		console.error('云函数执行错误:', error)
		return {
			success: false,
			error: error.message,
			stack: error.stack
		}
	}
}

// 测试数据格式
async function testPatternFileFormat() {
	console.log('=== 测试数据格式 ===')
	
	const collection = db.collection('sh_pattern')
	
	// 获取前10条记录进行测试
	const result = await collection
		.field({
			_id: true,
			pattern_file: true,
			file_name: true // 检查是否已存在
		})
		.limit(10)
		.get()
	
	const testResults = []
	
	result.data.forEach((item, index) => {
		let fileName = ''
		if (item.pattern_file && typeof item.pattern_file === 'string') {
			const lastSlashIndex = item.pattern_file.lastIndexOf('/')
			fileName = lastSlashIndex !== -1 
				? item.pattern_file.substring(lastSlashIndex + 1)
				: item.pattern_file
		}
		
		const testResult = {
			index: index + 1,
			id: item._id,
			pattern_file: item.pattern_file,
			current_file_name: item.file_name || null,
			extracted_file_name: fileName,
			needs_update: !item.file_name && fileName
		}
		
		testResults.push(testResult)
		
		console.log(`${index + 1}. ID: ${item._id}`)
		console.log(`   pattern_file: ${item.pattern_file}`)
		console.log(`   当前 file_name: ${item.file_name || '(无)'}`)
		console.log(`   提取的 file_name: ${fileName}`)
		console.log(`   需要更新: ${testResult.needs_update ? '是' : '否'}`)
		console.log('---')
	})
	
	// 统计需要更新的总数
	const countResult = await collection
		.where({
			pattern_file: db.command.exists(true),
			file_name: db.command.exists(false)
		})
		.count()
	
	return {
		success: true,
		action: 'test',
		sampleData: testResults,
		totalNeedUpdate: countResult.total,
		message: `测试完成。共有 ${countResult.total} 条记录需要更新 file_name 字段`
	}
}

// 执行更新
async function updatePatternFileNames() {
	console.log('=== 开始批量更新 ===')
	
	const collection = db.collection('sh_pattern')
	
	// 分批处理配置
	const batchSize = 50  // 云函数环境下建议较小的批次
	let skip = 0
	let totalUpdated = 0
	let totalErrors = 0
	let hasMore = true
	
	const updateLog = []
	
	while (hasMore) {
		console.log(`处理批次: ${skip + 1} - ${skip + batchSize}`)
		
		try {
			// 获取一批需要更新的数据
			const result = await collection
				.where({
					pattern_file: db.command.exists(true),
					file_name: db.command.exists(false)
				})
				.skip(skip)
				.limit(batchSize)
				.get()
			
			if (result.data.length === 0) {
				hasMore = false
				break
			}
			
			// 处理当前批次
			for (const item of result.data) {
				try {
					// 提取文件名
					let fileName = ''
					if (item.pattern_file && typeof item.pattern_file === 'string') {
						const lastSlashIndex = item.pattern_file.lastIndexOf('/')
						fileName = lastSlashIndex !== -1 
							? item.pattern_file.substring(lastSlashIndex + 1)
							: item.pattern_file
					}
					
					if (fileName) {
						// 更新记录
						await collection.doc(item._id).update({
							file_name: fileName
						})
						
						totalUpdated++
						updateLog.push({
							id: item._id,
							pattern_file: item.pattern_file,
							file_name: fileName,
							status: 'success'
						})
						
						console.log(`✅ 更新成功 - ${item._id}: ${fileName}`)
					} else {
						updateLog.push({
							id: item._id,
							pattern_file: item.pattern_file,
							file_name: null,
							status: 'skipped',
							reason: 'pattern_file为空或无效'
						})
						console.log(`⚠️ 跳过 - ${item._id}: pattern_file为空`)
					}
				} catch (error) {
					totalErrors++
					updateLog.push({
						id: item._id,
						pattern_file: item.pattern_file,
						status: 'error',
						error: error.message
					})
					console.error(`❌ 更新失败 - ${item._id}:`, error.message)
				}
			}
			
			skip += batchSize
			
			// 如果返回的记录数少于批次大小，说明没有更多数据了
			if (result.data.length < batchSize) {
				hasMore = false
			}
			
		} catch (error) {
			console.error(`批次处理错误 (skip: ${skip}):`, error)
			totalErrors++
			hasMore = false
		}
	}
	
	// 验证更新结果
	const verifyResult = await collection
		.where({
			pattern_file: db.command.exists(true),
			file_name: db.command.exists(false)
		})
		.count()
	
	const result = {
		success: totalErrors === 0,
		action: 'update',
		totalUpdated: totalUpdated,
		totalErrors: totalErrors,
		remainingCount: verifyResult.total,
		updateLog: updateLog.slice(-20), // 只返回最后20条日志避免数据过大
		summary: {
			message: `更新完成！成功更新 ${totalUpdated} 条记录，${totalErrors} 条记录更新失败，还有 ${verifyResult.total} 条记录待更新`,
			isComplete: verifyResult.total === 0
		}
	}
	
	console.log('=== 更新完成 ===')
	console.log(`成功: ${totalUpdated} 条`)
	console.log(`失败: ${totalErrors} 条`)
	console.log(`剩余: ${verifyResult.total} 条`)
	
	return result
}